package com.fofia.iotweb.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.fofia.iotweb.Contants.CacheContant;
import com.fofia.iotweb.Contants.SolonBootConfigDto;
import com.fofia.iotweb.cache.UserCache;
import com.fofia.iotweb.common.SecureHelper;
import com.fofia.iotweb.framework.core.RequestHelper;
import com.fofia.iotweb.web.dbdomain.models.admin.SysMenu;
import com.fofia.iotweb.web.dbdomain.models.admin.SysUser;
import com.fofia.iotweb.web.dbdomain.services.admin.SysMenuService;
import com.fofia.iotweb.web.dbdomain.services.admin.SysUserService;
import com.fofia.iotweb.web.dto.JsonResult;
import com.fofia.iotweb.web.dto.LoginUserDto;
import com.fofia.iotweb.web.dto.ResultAdaptDto;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import java.time.LocalDateTime;
import java.util.List;

@Controller
public class HomeController {

    @Inject
    private RequestHelper requestHelper;
    @Inject
    private UserCache userCache;
    @Inject
    private SysUserService userService;
    @Inject
    private SysMenuService menuService;
    //@Inject
    //private Ip2regionSearcher regionSearcher;
    @Inject
    private SolonBootConfigDto solonBootConfigDto;
    @Mapping("/login")
    public ModelAndView login(){

        return new ModelAndView("/home/login.ftl");
    }

    @Post
    @Mapping("/loginOn")
    public ResultAdaptDto loginOn(){
        String uname=requestHelper.getString("uname","");
        String pwd=requestHelper.getString("pwd","");
        //StaticLog.info("uname:{},pwd:{}",uname,pwd);
        if(StrUtil.isEmpty(uname)){
            return JsonResult.failure("用户名错误");
        }
        if(StrUtil.isEmpty(pwd)){
            return JsonResult.failure("密码错误");
        }
        SysUser user=userService.Login(uname,pwd);
        if(user!=null){
            if(!pwd.equals(user.getPassWord())){
                return JsonResult.failure("密码错误");
            }
            //生成token规则 key;loginName:loginTime;random
            String randomString= RandomUtil.randomString(20);
            String cookie=StrUtil.format("fofia_iot_web;{};{};{}","admin", DateUtil.now(),randomString);
            String token= SecureHelper.encryptDes(cookie);
            //写入cookie
            int expire= CacheContant.cookieExpire;//天-小时-分钟-秒
            Context.current().cookieSet("auth_token",token,expire);

            //写入redis
            LoginUserDto userDto=new LoginUserDto();
            userDto.setUserId(user.getId());
            userDto.setRoleId(user.getRoleId());
            userDto.setLoginName(uname);
            userDto.setEmail(userDto.getEmail());
            userDto.setUserName(user.getUserName());
            userDto.setTel(user.getMobilePhone());
            userDto.setGender(user.getGender());
            userDto.setDeptName("富华物联");
            userDto.setLoginTime(LocalDateTime.now());
            userDto.setLoginIp(requestHelper.getIp());
            userDto.setAvatar(user.getUserAvatar());
            if(user.getIsSuper()==1){
                userDto.setSuperRole(true);
            }
            userCache.setCache(userDto);
            //返回
             var ret=new ResultAdaptDto();
              ret.put("url","/");
              ret.setMessage("登录成功");
            return JsonResult.data(ret);
        }
        return JsonResult.failure("用户名或密码错误");
    }

    @Get
    @Mapping("/loginOut")
    public ModelAndView loginOut(){
        Context.current().cookieSet("auth_token","",0);
        return new ModelAndView("/home/login.ftl");
    }


    @Mapping("/")
    public ModelAndView index(){

        StaticLog.info("solonBootConfigDto:{},{}",solonBootConfigDto.isApilog(),solonBootConfigDto.isSqllog());
        String token=requestHelper.getUserName();
        LoginUserDto userDto=userCache.getCache(token);
        if(userDto==null){
            Context.current().cookieSet("auth_token","",0);
            return new ModelAndView("/home/login.ftl");
        }

        String ip=requestHelper.getIp();
       // String cityIpString=regionSearcher.getAddress(ip);
        StaticLog.info("登录Ip:{}",ip);

        List<SysMenu> menus=menuService.getAllMenus();
        String homeUrl="/home/test";
        return new ModelAndView("index.ftl")
                .put("userName",userDto.getUserName())
                .put("headImage",userDto.getAvatar())
                .put("homeUrl",homeUrl)
                .put("menus",menus);
    }

    @Mapping("/home/test")
    public ModelAndView test(){

        return new ModelAndView("/home/test.ftl")
                .put("title","使用模板界面的");
    }

    @Get
    @Mapping("/notFound")
    public ModelAndView notFound(){

        return new ModelAndView("/error/404.html");
    }
    @Get
    @Mapping("/home/switchSkin")
    public ModelAndView switchSkin(){
        return new ModelAndView("/home/switchSkin.ftl");
    }
}
